#install.packages("ISwR")
library(ISwR)

# 3. Probability and distributions -------------------------------------------


# 3.1 Random sampling -----------------------------------------------------

sample(1:40,5) # coge 5 valores del 1 al 40 aleatoriamente SIN REPETICION

sample(c("H","T"), 10, replace=T) # Simula 10 lanzamientos de moneda. Ovbiamente CON REPETICION

sample(c("succ", "fail"), 10, replace=T, prob=c(0.9, 0.1)) # alteramos las probabilidades

# 3.2 Probability calculations and combinatorics --------------------------

# la probabilidad de sacar 5 numeros de 40 sin repeticion y EN ORDEN:
1/prod(40:36)

# ahora la misma probabilidad pero sin importar el orden
prod(5:1)/prod(40:36)

#podriamos haber llegado al mismo resultado con la combinatoria
1/choose(40,5)


# 3.3 Discrete distributions ----------------------------------------------


# 3.4 Continuous distributions --------------------------------------------


# 3.5 The built-in distributions in R -------------------------------------


# 3.5.1 Densities ---------------------------------------------------------

x <- seq(-4,4,0.1)
plot(x,dnorm(x),type="l")

curve(dnorm(x), from=-4, to=4, col="green") # como alternativa

# para distribuciones discretas
x <- 0:50
bin <- dbinom(x,size=50,prob=.33) # distribucion binomial con n=50 y p=0.33
plot(x,bin,type="h")


# 3.5.2 Cumulative distribution functions ---------------------------------

1-pnorm(160,mean=132,sd=13) # probabilidad de que sea mayor que 160 (por el 1-)


# 3.5.3 Quantiles ---------------------------------------------------------

# The quantile function is the inverse of the cumulative distribution function.

sd <- 24
n <- 10
sem <- sigma/sqrt(n)
lim_inf <- sem * qnorm(0.025)
lim_sup <- sem * qnorm(0.975)
f.auxi <- function(j){
  medias <- sapply(1:100, function (i){mean(rnorm(n, sd=sd))})
  fuera_intervalo <- sum(medias<lim_inf | medias>lim_sup)
}

media_fuera_intervalo <- mean(sapply(1:100, f.auxi))
media_fuera_intervalo

# 3.6 Exercises -----------------------------------------------------------


# 3.1 Calculate the probability for each of the following events: 
# (a) A standard normally distributed variable is larger than 3. 
# (b) A normally distributed variable with mean 35 and standard deviation 6 is larger than 42. 
# (c) Getting 10 out of 10 successes in a binomial distribution with probability 0.8. 
# (d) X < 0.9 when X has the standard uniform distribution. 
# (e) X > 6.5 in a c2 distribution with 2 degrees of freedom.
# a
1 - pnorm(3)
# b
1 - pnorm(42, mean=35, sd=6)
# c
dbinom(10, size=10, prob=0.8)
# d
punif(0.9)
# e
1 - pchisq(6.5, df=2)

# 3.2 A rule of thumb is that 5% of the normal distribution lies outside an interval approximately ±2s about the mean. 
# To what extent is this true? 
# Where are the limits corresponding to 1%, 0.5%, and 0.1%? 
# What is the position of the quartiles measured in standard deviation units?
sd <- 10
2*pnorm(-2 * sd, sd=sd)*100

abs(qnorm(1-5/200, sd=sd)/sd)
abs(qnorm(1-1/200, sd=sd)/sd)
abs(qnorm(1-0.5/200, sd=sd)/sd)
abs(qnorm(1-0.1/200, sd=sd)/sd)

qnorm(.25)
qnorm(.75)

# 3.3 For a disease known to have a postoperative complication frequency of 20%, a surgeon suggests a new procedure. 
# He tests it on 10 patients and there are no complications. What is the probability of operating on 10
# patients successfully with the traditional method?
dbinom(10, 10,prob=0.8)
# o de otra manera
dbinom(0, 10,prob=0.2)

# 3.4 Simulated coin-tossing can be done using rbinom instead of sample. How exactly would you do that?

xaux <- rbinom(10, size=1, prob=0.5)
xaux[xaux==1] <- "H"
xaux[xaux==0] <- "T"
# tambien funcionara 
ifelse(rbinom(10, 1, .5) == 1, "H", "T")
# o incluso
c("H", "T")[1 + rbinom(10, 1, .5)]